import React from 'react'
import router from 'umi/router'
import PropTypes from 'prop-types'
import { Breadcrumb, Icon, Button } from 'antd'
import { Link } from 'react-router-dom'
import pathToRegexp from 'path-to-regexp'
import styles from './Layout.less'
import { routes } from 'setting'

const Bread = ({ prodMenu, location }) => {
  // 匹配当前路由
  let pathArray = []
  let current
  let isHaveBread = ''
  for (let index in prodMenu) {
    if (prodMenu[index].route && pathToRegexp(prodMenu[index].route).exec(location.pathname)) {
      isHaveBread = false
      break
    } else { 
      isHaveBread = true
    }
  }
  
  if(isHaveBread){
    routes.find((value) => {
      if(value && pathToRegexp(value.route).exec(location.pathname)){
        return current = value
      }else{
        return false
      }
    })
  }
 
  const getPathArray = (item) => {
    pathArray.unshift(item)
    if(item.route){
      routes.find((value) => {
        if(item['route']!==value.route&&item['route'].includes(value.route)&&!pathArray.includes(value)){
          return getPathArray(value)
        }else{
          return false
        }
      })
    }
  }

  let paramMap = {}
  if (!current) {
    pathArray.push({
      id: 404,
      name: 'Not Found',
    })
  } else {
    getPathArray(current)

    let keys = []
    let values = pathToRegexp(current.route, keys).exec(location.pathname.replace('#', ''))
    if (keys.length) {
      keys.forEach((currentValue, index) => {
        if (typeof currentValue.name !== 'string') {
          return
        }
        paramMap[currentValue.name] = values[index + 1]
      })
    }
  }

  // 递归查找父级
  const breads = pathArray.map((item, key) => {
    const content = (
      <span>{item.icon
        ? <Icon type={item.icon} style={{ marginRight: 4 }} />
        : ''}{item.name}</span>
    )
    return (
      <Breadcrumb.Item key={key}>
        {((pathArray.length - 1) !== key)
          ? <Link to={pathToRegexp.compile(item.route || '')(paramMap) || '#'}>
            {content}
          </Link>
          : content}
      </Breadcrumb.Item>
    )
  })

  return (
    <div className={styles.bread}>
      <Button type="primary" shape="circle" icon="left" size="small" className={styles.goback}  onClick={()=>{router.goBack()}}/>
      <Breadcrumb>
        {breads}
      </Breadcrumb>
    </div>
  )
}

Bread.propTypes = {
  prodMenu: PropTypes.array,
  location: PropTypes.object,
}

export default Bread
